package io.github.wanggit.antrpc.commons.utils;

import io.github.wanggit.antrpc.commons.bean.Host;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class ApplicationNameUtil {

    private ApplicationNameUtil() {
        throw new IllegalStateException();
    }

    /**
     * @param exposeIp ip
     * @param appName spring.application.name
     * @param rpcPort rpc port
     * @return spring_application_name@ip:rpcPort
     */
    public static String getApplicationName(String exposeIp, String appName, int rpcPort) {
        return appName + "@" + exposeIp + ":" + rpcPort;
    }

    /**
     * @param serviceFullName spring_application_name@ip:rpcPort
     * @return host
     */
    public static Host getHost(String serviceFullName) {
        checkServiceFullName(serviceFullName);
        return Host.parse(serviceFullName.split("@")[1]);
    }

    /**
     * @param serviceFullName spring_application_name@ip:rpcPort
     * @return spring_application_name
     */
    public static String getSimpleAppName(String serviceFullName) {
        checkServiceFullName(serviceFullName);
        return serviceFullName.split("@")[0];
    }

    private static void checkServiceFullName(String serviceFullName) {
        if (null == serviceFullName) {
            throw new IllegalArgumentException("serviceFullName is null.");
        }
        String[] tmps = serviceFullName.split("@");
        if (tmps.length <= 1) {
            throw new IllegalArgumentException(
                    "serviceFullName format is \"applicationName@localhost:6060\"");
        }
    }
}
